package top.lywivan.netty.reactor.cnxn;


import top.lywivan.netty.reactor.Server;

import java.io.IOException;
import java.net.InetSocketAddress;

public  abstract class ServerCnxnFactory {

    public static final String SERVER_CNXN_FACTORY = "serverCnxnFactory";

    private static final String MAX_CONNECTION = "maxCnxns";
    public static final int MAX_CONNECTIED_DEFAULT = 0;


    // 服务端已接收的连接数
    protected int maxCnxns;


    /**
     * 创建服务端连接管理工厂
     * @return
     */
    public static ServerCnxnFactory createFactory() throws IOException {
        //支持配置

        String serverCnxnFactoryName = System.getProperty(SERVER_CNXN_FACTORY);
        if (serverCnxnFactoryName == null) {
            serverCnxnFactoryName = NIOServerCnxnFactory.class.getName();
        }

        // 实例化
        try {
            ServerCnxnFactory serverCnxnFactory = (ServerCnxnFactory) Class.forName(serverCnxnFactoryName).getDeclaredConstructor().newInstance();
            return serverCnxnFactory;
        }catch (Exception e) {
            throw new IOException(e.getMessage());
        }
    }

    public abstract void configure(InetSocketAddress clientPortAddress, int maxClientCnxns, int clientPortListenBacklog, boolean secure) throws IOException;

    public  void startup(Server server) throws IOException,InterruptedException{
        startup(server,true);
    }

    public abstract void startup(Server server,boolean startServer) throws IOException,InterruptedException;


    protected void initMaxCnxns() {
        maxCnxns = Integer.getInteger(MAX_CONNECTION,MAX_CONNECTIED_DEFAULT);
        if (maxCnxns ==0) {
            maxCnxns = MAX_CONNECTIED_DEFAULT;
        }

    }
}
